package com.java.example.ui.viewmodel

import android.app.Application
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson2.JSON
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.VibrateUtils
import com.google.gson.Gson
import com.java.example.app.AccountManager
import com.java.example.app.Constant
import com.java.example.bean.UserProfile
import com.java.example.databinding.ActivityLoginBinding
import com.java.example.network.BaseObserver
import com.java.example.network.ICallBack
import com.java.example.network.RequestUtil
import com.java.example.network.response.BaseResponse
import com.java.example.network.response.LoginResponse
import com.java.example.ui.activity.AgreementActivity
import com.java.example.ui.activity.PolicyActivity
import com.java.example.util.AccountUtil
import com.java.example.util.loader.LatteLoader
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class LoginViewModel(application: Application) : AndroidViewModel(application) {
    lateinit var binding: ActivityLoginBinding
    var phone: MutableLiveData<String> = MutableLiveData("")
    var password: MutableLiveData<String> = MutableLiveData("")
    var checked: MutableLiveData<Boolean> = MutableLiveData(false)
    var isDisplay = false
    val REQUEST_CODE: Int = 1024
    var gotoMain: (() -> Unit)? = null
    var isShowBack: Boolean = false;
    var disposable: CompositeDisposable = CompositeDisposable()

    fun login(context: Context) {
        if (!isAvaliable2Commit(phone.value!!, password.value!!)) {
            return
        }
        if (!checked.value!!) {
            VibrateUtils.vibrate(200)
            KeyboardUtils.hideSoftInput(binding.btnLogin)
            viewModelScope.launch {
                delay(500)
                binding.checkbox.animate().scaleY(1.3f).scaleX(1.3f).withEndAction {

                    binding.checkbox.animate().scaleY(1f).scaleX(1f).start()
                }.start()
            }
            ToastUtils.showLong("请阅读并同意用户使用协议！")
            return
        }
        RequestUtil.instance.login(phone.value!!, password.value!!).subscribe(BaseObserver(object : ICallBack<LoginResponse> {
            override fun onStart(d: Disposable) {
                disposable.add(d)
                LatteLoader.showLoading(context)
            }

            override fun onFail(tResponse: BaseResponse<LoginResponse>?, e: Throwable?) {
                tResponse?.let {
                    ToastUtils.showShort(tResponse.message)
                } ?: run {
                    ToastUtils.showShort(e?.message)
                }
            }

            override fun onResponse(t: LoginResponse?) {
                gotoMain!!.invoke()
            }

            override fun onEnd() {
                LatteLoader.stopLoading()
            }
        }))
    }

    private fun isAvaliable2Commit(phone: String, password: String): Boolean {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort("请输入手机号码")
            return false
        }
        if (phone.length > 11) {
            ToastUtils.showShort("请输入正确的手机号码")
            return false
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtils.showShort("请输入密码")
            return false
        }
        return true
    }


    private fun saveAccount(context: Context, response: String, password: String) {
//        val userProfile = JSONObject.parseObject(response, UserProfile::class.java)
        val userProfile = Gson().fromJson(response, UserProfile::class.java)
        val jsonObject = JSON.parseObject(response)
        var agencyId = ""
        var isAgency = false
        val store = jsonObject.getJSONObject("store")
        //磁盘缓存
        CacheDiskUtils.getInstance().put(Constant.USER_CACHE, userProfile)
        AccountUtil.putObject(context, Constant.USER_CACHE, userProfile)
        //放入内存
        AccountManager.setUserProfile(userProfile)
        SPUtils.getInstance().put(Constant.IS_LOGIN_STATE, true)

    }


    fun switchVersion(): Boolean {
        val versionSwitch = SPUtils.getInstance().getString(Constant.VERSION_SWITCH)
        if (versionSwitch == Constant.OFFICAL_HOST) {
            SPUtils.getInstance().put(Constant.VERSION_SWITCH, Constant.TEST_HOST, true)
            AppUtils.exitApp()
        } else if (versionSwitch == Constant.TEST_HOST) {
            SPUtils.getInstance().put(Constant.VERSION_SWITCH, Constant.OFFICAL_HOST, true)
            AppUtils.exitApp()
        }
        return true
    }

    fun agreement(context: Context) {
        context.startActivity(Intent(context, AgreementActivity::class.java))
    }

    fun secret(context: Context) {
        context.startActivity(Intent(context, PolicyActivity::class.java))
    }

    fun eye(view: View, context: Context) {
    }

    fun forgetpassword(context: Context) {
    }

    fun smsLogin(view: View, context: Context) {
    }

    override fun onCleared() {
        super.onCleared()
        disposable.clear()
    }
}

